package www.wmx.com.xssc.util.tptq;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.bouncycastle.asn1.ocsp.ResponseData;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Recover;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.HttpServerErrorException;
import www.wmx.com.xssc.domain.vo.request.RequestPicture;
import www.wmx.com.xssc.domain.vo.request.XsscRequest;
import www.wmx.com.xssc.domain.vo.response.ResponseDataDTO;
import www.wmx.com.xssc.domain.vo.response.ResponsePicture;
import www.wmx.com.xssc.util.common.JsonUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Component
@Slf4j
public class ImageExtractionUtil {

    private static String send_url;
    private static String user_url;

    static {
        Properties properties = new Properties();
        InputStream inputStream = ImageExtractionUtil.class.getResourceAsStream("/config.properties");
        try {
            properties.load(inputStream);
            send_url = properties.getProperty("send.picture.url");
            user_url = properties.getProperty("msg.send.url");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



    @Recover
    public ResponsePicture recover(Exception e, RequestPicture requestPicture) {
        log.error("All retry attempts failed for requestPicture: {}", requestPicture, e);
        log.error("OCR服务响应失败，请及时排查!", requestPicture, e);
        return null;
    }

    @Retryable(value = {Exception.class}, maxAttempts = 3, backoff = @Backoff(delay = 5000, multiplier = 2))
    public ResponsePicture sendFormPost(RequestPicture requestPicture) throws Exception {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        List<RequestPicture> list = new ArrayList<>();
        list.add(requestPicture);
        Map<String, Object> map = new HashMap<>();
        map.put("fileList", list);
        String JSONBody = JSONUtil.toJsonStr(map);
        //设置超时时间
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(60000)
                .setConnectionRequestTimeout(60000).setSocketTimeout(60000).build();
        HttpPost httpPost = new HttpPost(send_url);
        httpPost.setConfig(requestConfig);
        httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
        httpPost.setEntity(new StringEntity(JSONBody));
        CloseableHttpResponse response = httpClient.execute(httpPost);
        log.info("OCR服务响应状态码：{}", response.getStatusLine().getStatusCode());
        log.info("OCR服务响应结果：{}",response.getEntity());
        HttpEntity entity = response.getEntity();
        String responseContent = EntityUtils.toString(entity, "UTF-8");
        List<ResponsePicture> responsePictures = JSONArray.parseArray(responseContent, ResponsePicture.class);
        ResponsePicture picture = responsePictures.get(0);
        response.close();
        httpClient.close();
        return picture;
    }

    @Recover
    public void recover(Exception e, XsscRequest query, File file, String FileName) {
        log.error("消息推送服务重试失败，所有重试尝试均已用尽。请求参数: XsscRequest={}, FileName={}", query, FileName, e);
        // 可以在这里添加告警或其他处理逻辑
    }


    @Retryable(
            value = {IOException.class, HttpServerErrorException.class},
            maxAttempts = 3,
            backoff = @Backoff(delay = 8000, multiplier = 2)
    )
    public void HttpClientServiceSuccess(XsscRequest query, File file, String FileName) {

        log.info("发送消息的路径：{}", user_url);
        String msg = FileName.replaceAll(".pdf","") + "已完成形式审查，请查看";
        String title = "形式审查"+query.getNd().substring(0,4)+"年度形式审查报告";

        String json = JsonUtils.buildNotification(msg, title, query.getUserCode());
        CloseableHttpClient httpClient = HttpClients.createDefault();
        try {
            HttpPost httpPost = new HttpPost(user_url);
            StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON.withCharset(StandardCharsets.UTF_8));
            httpPost.setEntity(entity);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");

            CloseableHttpResponse response = httpClient.execute(httpPost);
            try {
                HttpEntity responseEntity = response.getEntity();
                if (responseEntity != null) {
                    int statusCode = response.getStatusLine().getStatusCode();
                    log.info("发送消息的相应状态码：{}", statusCode);
                    if (statusCode == 200) {
                        // 读取响应体
                        String jsonResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
                        log.info(jsonResponse);
//                        // 使用Gson解析JSON
//                        Gson gson = new Gson();
//                        Type responseDataType = new TypeToken<ResponseData>() {
//                        }.getType();
                        JSONObject jsonObject = JSONObject.parseObject(jsonResponse);
                        ResponseDataDTO responseData = jsonObject.toJavaObject(ResponseDataDTO.class);
                        String code = responseData.getCode();
                        if (!code.equals("200")) {
                            log.error("推送消息失败:{}", responseData.getMsg());
                        } else {
                            log.info("推送消息成功");
                        }
                    } else {
                        log.info("发送消息的相应状态码：{}", statusCode);
                    }
                } else {
                    log.error("推送消息失败");
                }
            } finally {
                response.close();
            }
        } catch (IOException e) {
            log.error("网络连接失败，发送消息失败！");
            e.printStackTrace();
        } finally {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static boolean isImageFile(String filePath,String basePath) {
        String[] imageExtensions = {"jpg", "png"};
        File file = new File(basePath + filePath);
        String extension = getFileExtension(file);
        if(! (file.exists() && file.isFile())){
            return false;
        }
        for (String ext : imageExtensions) {
            if (extension.equalsIgnoreCase(ext)) {
                return true;
            }
        }
        return false;
    }

    private static String getFileExtension(File file) {
        String fileName = file.getName();
        if (fileName.lastIndexOf(".") != -1 && fileName.lastIndexOf(".") != 0) {
            return fileName.substring(fileName.lastIndexOf(".") + 1);
        }
        return "";
    }





}
